package com.quanxiaoha.xiaohashu.gateway.filter;


import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: jingyan_liu
 * @CreateTime: 2025-07-13
 * @Description: 转发请求时，将用户 ID 添加到 Header 请求头中，透传给下游服务
 * @Version: 1.0
 */


@Component
@Slf4j
@Order(-99)
public class AddUserId2HeaderFilter implements GlobalFilter {
	
	/**
	 * 请求头中，用户 ID 的键
	 */
	private static final String HEADER_USER_ID = "userId";
	
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		log.info("==================> TokenConvertFilter");
		
		// 用户 ID
		long userId;
		try {
			// 获取当前登录用户的 ID
			userId = StpUtil.getLoginIdAsLong();
		} catch (Exception e) {
			// 若没有登录，则直接放行
			return chain.filter(exchange);
		}
		
		log.info("## 当前登录的用户 ID: {}", userId);
		
		Long finalUserId = userId;
		ServerWebExchange newExchange = exchange.mutate()
				.request(builder -> builder.header(HEADER_USER_ID, String.valueOf(finalUserId))) // 将用户 ID 设置到请求头中
				.build();
		return chain.filter(newExchange);
	}
}
